package com.bootssm.controller;

import com.bootssm.entity.*;
import com.bootssm.service.ShopListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/shoplist")
public class ShopListController {
    @Autowired
    ShopListService shopListService;

    @PostMapping("/findAll")
    public PageView<ShopList> finAll(@RequestBody ShopListVO shopListVO){
        Integer page = shopListVO.getPage(); //拿到前端页码
        int start = (page - 1) * shopListVO.getSize();//计算出来开始位置
        //把开始位置设置到studentVO中
        shopListVO.setStart(start);

        //获取总条数
        Integer count = shopListService.getCount(shopListVO);
        List<ShopList> shopLists = shopListService.findAll(shopListVO);

        PageView<ShopList> pageView = new PageView<>();
        pageView.setDataList(shopLists); //数据
        pageView.setCount(count); //总条数

        return pageView;
    }

    @PostMapping("/deleteById")
    public Result deleteById(@RequestBody ShopList shopList){
        //根据ID删除数据库
        String id = shopList.getShopid(); //得到传递过来的ID
        shopListService.deleteById(id);

        return new Result("200","删除成功");
    }

    @PostMapping("/update")
    public Result update(@RequestBody ShopList shopList){

        try{
            shopListService.update(shopList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result("500","修改失败");
        }

        return new Result("200","修改成功");
    }

    @PostMapping("/save")
    public Result save(@RequestBody ShopList shopList){

        try{
            shopListService.save(shopList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result("500","保存失败");
        }

        return new Result("200","保存成功");
    }
}
